<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use think\facade\Db;
use think\facade\Log;

/**
 * Test控制器
 */
class Size extends AdminBase
{

    protected $model = null;



    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    /**
     * 尺寸列表
     */
    public function index()
    {
        $color_id = input('color_id');
        $list = table('size')->where(['color_id' => $color_id])->field('id,title')->order(['id' => 'asc'])->select()->toarray();
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $list,
        ];

        return json($data);
    }

    /**
     * 添加
     */
    public function add()
    {
        $post = input();
        try {
            if ($post['title']) {
                $post['title'] = sku_color_deal($post['title']);
            }
            if ($post['brand_id']) {
                $post['brand_id'] = $post['brand_id'];
            }
            if ($post['color_id']) {
                $post['color_id'] = $post['color_id'];
            }
            unset($post['s']);
            $result = table('size')->save($post);
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $size_id = input('size_id');
        $row = table('size')->where(['id' => $size_id])->find();
        if (empty($row)) {
            return error('数据不存在');
        }

        if ($this->request->isPost()) {
            $post = input();
            try {
                if ($post['title']) {
                    $post['title'] =  sku_color_deal($post['title']);
                }
                $result = table('size')->where(['id' => $size_id])->save(['title' => $post['title']]);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }

        return success('ok', $row);
    }

    /**
     * 删除
     *
     */
    public function delete()
    {
        $size_id = input('size_id');
        $result  =  table('size')->where(['id' => $size_id])->delete();
        if ($result) {
            return success('删除成功');
        }
        return error('删除失败');
    }
}
